<template>
  <div class="user-edit-container">
    <el-card class="edit-card">
      <template #header>
        <div class="card-header">
          <span>编辑用户信息</span>
        </div>
      </template>
      
      <el-form 
        v-loading="loading"
        :model="form" 
        :rules="rules"
        ref="formRef"
        label-width="120px" 
        class="user-form"
      >
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" disabled />
        </el-form-item>

        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" disabled />
        </el-form-item>

        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio :value="0">男</el-radio>
            <el-radio :value="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="form.roleId" placeholder="请选择角色">
            <el-option label="管理员" :value="'1'" />
            <el-option label="普通用户" :value="'0'" />
          </el-select>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input 
            v-model="form.email" 
            placeholder="请输入邮箱" 
            maxlength="25"
            show-word-limit
            @input="handleEmailInput"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitting">保存</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { colProps, ElMessage } from 'element-plus'
import { searchUser, updateUserInfo } from '@/api'

const route = useRoute()
const router = useRouter()
const formRef = ref(null)
const loading = ref(false)
const submitting = ref(false)

// 表单数据
const form = reactive({
  userId: '',
  username: '',
  name: '',
  gender: '',
  email: '',
  roleId: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
    { max: 25, message: '邮箱长度不能超过25个字符', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value && /[\u4e00-\u9fa5]/.test(value)) {
          callback(new Error('邮箱不能包含中文字符'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ],
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 获取用户信息
const fetchUserInfo = async (userId) => {
  loading.value = true
  try {
    const response = await searchUser({ userId })
    console.log('获取到的用户信息：', response)
    
    if (response.data.code === 200) {
      const userData = response.data.data
      // 更新表单数据
      Object.assign(form, {
        userId: userData.userId,
        username: userData.username,
        name: userData.name || '',
        gender: userData.gender,
        email: userData.email || '',
        roleId: userData.roleId
      })
      console.log("r:"+userData.roleId);
      console.log("form:"+form.roleId);
    } else {
      ElMessage.error(response.data.message || '获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息出错：', error)
    ElMessage.error('获取用户信息失败')
  } finally {
    loading.value = false
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        // 只提交必要的字段
        const submitData = {
          userId: form.userId,
          username: form.username,
          name: form.name.trim(),
          gender: form.gender,
          roleId: form.roleId
        }

        // 只有当邮箱有值且不为空时才添加
        if (form.email && form.email.trim()) {
          submitData.email = form.email.trim()
        }

        console.log('提交的数据:', submitData)

        const response = await updateUserInfo(submitData)
        if (response.data.code === 200) {
          ElMessage.success('保存成功')
          router.push('/usermanagement')
        } else {
          ElMessage.error(response.data.message || '保存失败')
        }
      } catch (error) {
        console.error('保存用户信息出错：', error)
        ElMessage.error('保存失败，请检查必填信息是否完整')
      } finally {
        submitting.value = false
      }
    } else {
      ElMessage.warning('请填写必要的信息')
    }
  })
}

// 返回上一页
const goBack = () => {
  router.push('/usermanagement')
}

// 页面加载时获取用户信息
onMounted(() => {
  const userId = route.params.userId
  if (userId) {
    fetchUserInfo(userId)
  }
})

// 在 script setup 中添加邮箱输入处理方法
const handleEmailInput = (value) => {
  // 移除中文字符
  form.email = value.replace(/[\u4e00-\u9fa5]/g, '')
}
</script>

<style scoped>
.user-edit-container {
  padding: 20px;
  height: 100%;
  background-color: #f0f2f5;
}

.edit-card {
  max-width: 800px;
  margin: 0 auto;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0,21,41,.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-form {
  margin-top: 20px;
  padding: 20px;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .user-edit-container {
    padding: 10px;
  }
  
  .edit-card {
    margin: 0;
  }
  
  .user-form {
    padding: 10px;
  }
}

/* 添加性别选项的样式 */
.el-radio-group {
  width: 100%;
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  .el-radio-group {
    display: flex;
    justify-content: flex-start;
    gap: 20px;
  }
}
</style>
  